﻿var nextSearchPage;
var l = 1;
var youtubeInit = new Array();

function listVideos(json, divid) {
    $j('#youTubeSearchVideos li.showMoreRow').remove();
    var ul = document.createElement('ul');
    ul.setAttribute('id', 'youtubelist');
    if (json.data.items) {
        for (var i = 0; i < json.data.items.length; i++) {
            var entry = json.data.items[i];
            var str = "";
            str += '<li onclick="selectVideo(\'' + entry.id + '\');" id=' + entry.id + ' class="unselectedVideo videoRow videoRowSecond">';
            str += '<a onclick="playVideo(\'' + entry.id + '\')" class="viewYouTubeVideo" href="#">';
            str += '<img title="' + entry.title + '" class="ytVideoImage" src="http://i.ytimg.com/vi/' + entry.id + '/2.jpg" >';
            str += '</a>';
            str += '<div class="ytVideoTitle">';
            str += '<span title="' + entry.title + '" class="videoTitleText">' + entry.title.substr(0, 30) + '</span> ';
            str += '(<span class="ytVideoLength">' + entry.uploaded.substr(0, 10) + '</span>)';
            str += '</div>';
            str += '<div class="ytVideoDetails"><div class="totalView">' + entry.viewCount + ' lượt xem</div>';
            str += '<span class="desc" title="' + entry.description + '">' + entry.description.substr(0, 150) + '</span>';
            str += '</div>';
            str += '</li>';
            $j('#youTubeSearchVideos').append(str);
        } 
        $j('#youTubeSearchVideos').append('<li class="showMoreRow videoRowSecond"><a onclick="addVideo(' + ((nextSearchPage++) * 50) + ')">Hiển thị thêm video...</a></li>');
    } else {
        $j('#youTubeSearchVideos').html('<div id="noSearchVideos" style="display: block;">Không tìm thấy kết quả với từ khóa mà bạn đã nhập vào.<br>Hãy thử với các từ khác.</div>');
    }
}

function insertVideos(div, typ, q, results, start) {
    start = start + 1;
    if (typ == "mostviewed") q = "Most Viewed";
    if (typ == "linked") q = "Most Linked";
    var script = document.createElement('script');
    if (typ == "search") {
        script.setAttribute('src', 'http://gdata.youtube.com/feeds/api/videos?q=' + q + '&v=2&start-index=' + start + '&max-results=' + results + '&format=5&alt=jsonc&callback=youtubeInit[' + l + ']');
        if (document.title) document.title = "Tìm kiếm: " + q.replace("+", " ") + " - YouTube";
    }
    if (typ == "hot") {
        script.setAttribute('src', 'http://gdata.youtube.com/feeds/api/standardfeeds/recently_featured?alt=jsonc&v=2&format=5&callback=youtubeInit[' + l + ']&start-index=1&max-results=50');
        if (document.title) document.title = "Recently Featured - YouTube Fast Search";
    }
    if (typ == "mostviewed") {
        script.setAttribute('src', 'http://gdata.youtube.com/feeds/api/standardfeeds/most_viewed?time=this_month&v=2&format=5&alt=jsonc&callback=youtubeInit[' + l + ']&start-index=1&max-results=50');
        if (document.title) document.title = "Most Viewed This Month - YouTube Fast Search";
    }

    if (typ == "linked") {
        script.setAttribute('src', 'http://gdata.youtube.com/feeds/api/standardfeeds/most_linked?time=this_month&v=2&format=5&alt=jsonc&callback=youtubeInit[' + l + ']&start-index=1&max-results=50');
        if (document.title) document.title = "Most Linked This Month - YouTube Fast Search";
    }

    if (typ == "user") {
        script.setAttribute('src', 'http://gdata.youtube.com/feeds/api/videos?author=' + q + '&v=2format=5&&max-results=' + results + '&alt=jsonc&callback=youtubeInit[' + l + ']');
    }


    if (typ == "playlist") {
        script.setAttribute('src', 'http://gdata.youtube.com/feeds/api/playlists/' + q + '/?&alt=jsonc&v=2&format=5&callback=youtubeInit[' + l + ']');
    }

    youtubeInit[l] = function(root) { listVideos(root, div); };
    script.setAttribute('id', 'jsonScript');
    script.setAttribute('type', 'text/javascript');
    document.documentElement.firstChild.appendChild(script);
}
function makeRequest(page) {
    clearList('youTubeSearchVideos');
    var tags = encodeURI(document.getElementById('searchYouTube').value);
    insertVideos('youTubeSearchVideos', 'search', tags, '50', '0');
}
function clearList(ul) {
    var list = document.getElementById(ul);
    while (list.firstChild) {
        list.removeChild(list.firstChild);
    }
}
function createPlaylist() {
    $j.ajax({
        type: "POST",
        url: "/WebServices/YoutubeService.asmx/GetAllYoutube",
        data: "{'productId':'" + proId + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(response) {
            var data = response.d;
            $j.each(data, function(index, youtube) {
                var str = "";
                str += '<li onclick="selectVideo(\'' + youtube.Id + '\');" id=' + youtube.Id + ' class="unselectedVideo videoRow videoRowSecond">';
                str += '<a onclick="playVideo(\'' + youtube.Id + '\')" class="viewYouTubeVideo" href="#">';
                str += '<img title="' + youtube.Title + '" class="ytVideoImage" src="http://i.ytimg.com/vi/' + youtube.Id + '/2.jpg" >';
                str += '</a>';
                str += '<div class="ytVideoTitle">';
                str += '<span title="' + youtube.Title + '" class="videoTitleText">' + youtube.Title.substr(0, 30) + '</span> ';
                str += '(<span class="ytVideoLength">' + youtube.TimeUpload + '</span>)';
                str += '</div>';
                str += '<div class="ytVideoDetails"><div class="totalView">' + youtube.Views + ' lượt xem</div>';
                str += '<span class="desc" title="' + youtube.Description + '">' + youtube.Description.substr(0, 150) + '</span>';
                str += '</div>';
                str += '</li>';
                $j('#youTubeCurrentVideos').append(str);
            });
        },
        failure: function(msg) {
            alert(msg);
        }
    });
}
$j('#searchYouTube').bind('keypress', function(event) {
    if (event.keyCode == 13) {
        $j('#findVideosButton').trigger('click');
        return false;
    }
    return true;
});
$j(function () {
    $j('#addYouTubeVideos').attr('disabled', 'disabled');
    $j('#removeYouTubeVideos').attr('disabled', 'disabled');
    $j('#addYouTubeVideos').bind('click', function () {
        if ($j('#youTubeSearchVideos li.selectedVideo').size() < 1) { return; }
        $j('#youTubeSearchVideos li.selectedVideo').each(function () {
            var videoId = $j(this).attr('id');
            $j(this).removeClass('selectedVideo').addClass('unselectedVideo').hide();
            if ($j('#youTubeCurrentVideos #' + videoId).size() < 1) {
                $j('#youTubeCurrentVideos').append('<li onclick="selectVideo(\'' + videoId + '\');" id=' + videoId + ' class="unselectedVideo videoRow">' + $j(this).html() + '</li>');
                $j(this).attr('id', videoId + '_copy');
                // Insert DB
                var videoTitle = $j("#youTubeCurrentVideos #" + videoId + " div.ytVideoTitle span.videoTitleText").html();
                var videoDate = $j('#youTubeCurrentVideos li#' + videoId + ' div.ytVideoTitle span.ytVideoLength').html();
                var videoViews = $j('#youTubeCurrentVideos li#' + videoId + ' div.ytVideoDetails div.totalView').html().split(' ')[0];
                var videoDesc = $j('#youTubeCurrentVideos li#' + videoId + ' div.ytVideoDetails span.desc').html();
                if (videoViews == "undefined") videoViews = 0;
                videoTitle = videoTitle.replace(/'/g, '');
                videoDesc = videoDesc.replace(/'/g, '');
                var querystring =
                            "{" +
                                "'videoId':'" + videoId + "'," +
                                "'productId':'" + proId + "'," +
                                "'title':'" + videoTitle + "'," +
                                "'views':'" + videoViews + "'," +
                                "'timeUpload':'" + videoDate + "'," +
                                "'desc':'" + videoDesc + "'," +
                                "'random':'" + random + "'" +
                            "}";
                $j.ajax({
                    type: "POST",
                    url: "/WebServices/YoutubeService.asmx/InsertYoutube",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    data: querystring,
                    success: function (response) {
                        console.log(response.d);
                        $j('#noCurrentVideos').hide();
                        $j('#youTubeCurrentVideos').show();
                    },
                    failure: function (msg) { /*alert(msg);*/ },
                    error: function (xhr, ajaxOptions, thrownError) { /*alert(xhr.status + ': ' + thrownError);*/ }
                });
            }
        });
        $j('#addYouTubeVideos').attr('disabled', 'disabled');
    });

    $j('#removeYouTubeVideos').bind('click', function () {
        $j('#youTubeCurrentVideos li.selectedVideo').each(function () {
            var videoId = $j(this).attr('id');
            $j(this).remove();
            $j('#' + videoId + '_copy').attr('id', videoId).show();
            $j.ajax({
                type: "POST",
                url: "/WebServices/YoutubeService.asmx/DeleteYoutube",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: "{'videoId':'" + videoId + "'}",
                success: function (response) { },
                failure: function (msg) { alert(msg); },
                error: function (xhr, ajaxOptions, thrownError) { alert(xhr.status + ': ' + thrownError); }
            });
        });

        $j('#youTubeSearchVideos li, #youTubeCurrentVideos li').removeClass('videoRowFirst').removeClass('videoRowSecond');
        $j('#youTubeSearchVideos li:odd, #youTubeCurrentVideos li:odd').addClass('videoRowFirst');
        $j('#youTubeSearchVideos li:even, #youTubeCurrentVideos li:even').addClass('videoRowSecond');

        if ($j('#youTubeCurrentVideos li').size() < 1) {
            $j('#youTubeCurrentVideos').hide();
            $j('#noCurrentVideos').show();
            $j('#removeYouTubeVideos').attr('disabled', 'disabled');
        }

        if ($j('#youTubeCurrentVideos li.selectedVideo').size() > 0) {
            $j('#removeYouTubeVideos').removeAttr('disabled');
        } else {
            $j('#removeYouTubeVideos').attr('disabled', 'disabled');
        }
    });

    $j('#findVideosButton').bind('click', function () {
        if ($j('#searchYouTube').val().replace(/ /g, '') == '' || $j('#searchYouTube').val() == $j.data($j('#searchYouTube').get(0), "origValue")) {
            alert(lang.VideoPleaseEnterSearchTerm);
            $j('#searchYouTube').focus();
            return;
        }
        nextSearchPage = 1;

        clearList('youTubeSearchVideos');
        var tags = encodeURI(document.getElementById('searchYouTube').value);
        insertVideos('youTubeSearchVideos', 'search', tags, '50', '0');

        return false;
    });

    $j('#youTubeSearchVideos').click(function () {
        return false;
    });


    $j('#saveVideo').bind('click', function () {
        $j.post("/WebServices/YoutubeService.asmx/DeleteByProductId", { productId: proId }, function (result) { });
        $j('#youTubeCurrentVideos li').each(function () {
            var videoid = $j(this).attr('id');
            var titleY = $j('#youTubeCurrentVideos li#' + videoid + ' div.ytVideoTitle span.videoTitleText').html();
            var dateY = $j('#youTubeCurrentVideos li#' + videoid + ' div.ytVideoTitle span.ytVideoLength').html();
            var totalView = $j('#youTubeCurrentVideos li#' + videoid + ' div.ytVideoDetails div.totalView').html().split(' ')[0];
            var descY = $j('#youTubeCurrentVideos li#' + videoid + ' div.ytVideoDetails span.desc').html();
            $j.post("/WebServices/YoutubeService.asmx/Insert", {
                videoId: videoid,
                proId: proId,
                title: titleY,
                date: dateY,
                totalView: totalView,
                desc: descY
            }, function (result) { });
        });
    });
});

function playVideo(id) {
    var videoTitle = $j('#youTubeCurrentVideos li#' + id + ' div.ytVideoTitle span.videoTitleText').html();
    if (videoTitle == null) {
        videoTitle = $j('#youTubeSearchVideos li#' + id + ' div.ytVideoTitle span.videoTitleText').html();
    }
    $j.iModal({
        type: 'ajax',
        title: videoTitle,
        onOpen: function() {
            $j('.closeModalButton').bind('click', function() {
                $j.iModal.close();
            });
            $j('#ModalContainer').show();
        },
        buttons: '<input type="button" class="closeModalButton" value="Close"/>',
        url: 'http://www.youtube.com/v//' + id + '&hl=en&fs=1&',
        width: 450,
        height:345
    });

    return false;
}

function addVideo(index) {
    var tags = encodeURI(document.getElementById('searchYouTube').value);
    insertVideos('youTubeSearchVideos', 'search', tags, '50', index);
}

function selectVideo(id) {
    if ($j('#youTubeSearchVideos li#' + id + '').hasClass('selectedVideo')) {
        $j('#youTubeSearchVideos li#' + id + '').removeClass('selectedVideo').addClass('unselectedVideo');
    } else {
        $j('#youTubeSearchVideos li#' + id + '').addClass('selectedVideo').removeClass('unselectedVideo');
    }
    if ($j('#youTubeCurrentVideos li#' + id + '').hasClass('selectedVideo')) {
        $j('#youTubeCurrentVideos li#' + id + '').removeClass('selectedVideo').addClass('unselectedVideo');
    } else {
        $j('#youTubeCurrentVideos li#' + id + '').addClass('selectedVideo').removeClass('unselectedVideo');
    }

    if ($j('#youTubeSearchVideos li.selectedVideo').size() > 0) {
        $j('#addYouTubeVideos').removeAttr('disabled');
    } else {
        $j('#addYouTubeVideos').attr('disabled', 'disabled');
    }

    if ($j('#youTubeCurrentVideos li.selectedVideo').size() > 0) {
        $j('#removeYouTubeVideos').removeAttr('disabled');
    } else {
        $j('#removeYouTubeVideos').attr('disabled', 'disabled');
    }
}
function ShowLoading() {
    if (typeof (disableLoadingIndicator) != 'undefined' && disableLoadingIndicator) {
        return;
    }
    var windowWidth = $j(window).width();
    var scrollTop;
    if (self.pageYOffset) {
        scrollTop = self.pageYOffset;
    }
    else if (document.documentElement && document.documentElement.scrollTop) {
        scrollTop = document.documentElement.scrollTop;
    }
    else if (document.body) {
        scrollTop = document.body.scrollTop;
    }
    $j('#AjaxLoading').css('position', 'absolute');
    $j('#AjaxLoading').css('top', scrollTop + 'px');
    $j('#AjaxLoading').css('left', parseInt((windowWidth - 150) / 2) + "px");
    $j('#AjaxLoading').show();
}

function HideLoading() {
    $j('#AjaxLoading').hide();
}

$j(document).ready(function() {
    $j('html').ajaxStart(function() {
        ShowLoading();
    });

    $j('html').ajaxComplete(function() {
        HideLoading();
    });
    $j('.InitialFocus').focus();
});

